package com.eatme.dao;

import com.eatme.model.BasicList;
import org.apache.wicket.extensions.markup.html.repeater.data.table.filter.IFilterStateLocator;
import org.apache.wicket.extensions.markup.html.repeater.util.SortParam;
import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider;
import org.apache.wicket.model.IModel;

import java.util.Iterator;

public class BasicListDataProvider extends SortableDataProvider<BasicList>
        implements
        IFilterStateLocator {

    /**
     * dao that will be used to retrieve the list of contacts
     */
    private final BasicListDao dao;

    /**
     * reuse the contact entity to store filter information
     */
    private BasicList filter = new BasicList();

    private QueryParam queryParam;

    public void setQueryParam(QueryParam queryParam) {
        this.queryParam = queryParam;
    }

    public Object getFilterState() {
        return filter;
    }

    public void setFilterState(Object state) {
        filter = (BasicList) state;
    }

    public BasicListDataProvider(BasicListDao dao) {
        this.dao = dao;

        // set the default sort
        setSort("id", true);
    }

    /**
     * Gets an iterator for the subset of contacts.
     *
     * @param first offset for the first row of data to retrieve
     * @param count number of rows to retrieve
     * @return iterator capable of iterating over {first, first+count} contacts
     */
    public Iterator<BasicList> iterator(int first, int count) {
        SortParam sp = getSort();
        if (queryParam == null) {
            queryParam = new QueryParam(first, count, sp.getProperty(), sp.isAscending());
        } else {
            queryParam.setFirst(first);
            queryParam.setCount(count);
            queryParam.setSort(sp.getProperty());
            queryParam.setSortAsc(sp.isAscending());
        }
        return dao.find(queryParam, filter);
    }

    /**
     * Gets total number of items in the collection.
     *
     * @return total item count
     */
    public int size() {
        return dao.count(filter);
    }

    /**
     * Converts the object in the collection to its model representation. A good
     * place to wrap the object in a detachable model.
     *
     * @param object The object that needs to be wrapped
     * @return The model representation of the object
     */
    public IModel<BasicList> model(BasicList object) {
        return new DetachableBasicListModel(object, dao);
    }

}
